#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<unistd.h>
#include<unistd.h>
#include<time.h>
#include<mysql/mysql.h>
#include<time.h>
int handData(char *buf,int confd)
{
    char type[3];
    memset(type,0,3);
    strncpy(type,buf+1,2);//#01|andy|123
    MYSQL mysql;
    MYSQL_RES *result=NULL;
    MYSQL_ROW row;
	printf("buf=%s\n",buf);
    mysql_init(&mysql);
    if(mysql_real_connect(&mysql,"127.0.0.1","root","shenboyuan","qq",0,NULL,0)==NULL)
    {
        printf("connect error\n");
        return -1;
    }//xuyaogenjufanhuizhishifoushinullzhizhenlaipanduanshifoulianjiechengong
    type[2]='\0';
    if(strcmp(type,"01")==0)//zhuce
    {
        char uName[32];
        char pWord[32];
        sscanf(buf+4,"%[^|]|%s",uName,pWord);
        char sqlStr[1024]={0};
        sprintf(sqlStr,"select * from UserTb where UserName='%s'",uName);
        if(mysql_query(&mysql,sqlStr)!=0)
        {
            printf("#01select error:%s\n%s\n",mysql_error(&mysql),sqlStr);
            return -1;
        }
        result=mysql_store_result(&mysql);
        if(result==NULL)
        {
            printf("result error:%s\n",mysql_error(&mysql));
            return -1;
        }
        row=mysql_fetch_row(result);
        if(row)
	{
            write(confd,"#01|1|UserExist",15);
		printf("#05|1|UserExist\n");
	}
        else
        {
            write(confd,"#01|0|RegSuccess",16);
		printf("#01|0|RegSuccess\n");
            sprintf(sqlStr,"insert into UserTb values('%s','%s',0,-1)",uName,pWord);
            if(mysql_query(&mysql,sqlStr)!=0)
            {
                printf("#01insert error:%s\n%s\n",mysql_error(&mysql),sqlStr);
                return -1;
            }
        }
    }
    if(strcmp(type,"02")==0)
    {
        char uName[32];
        char pWord[32];
        sscanf(buf+4,"%[^|]|%s",uName,pWord);
        char sqlStr[1024]={0};
        sprintf(sqlStr,"select * from UserTb where UserName='%s' and password='%s'",uName,pWord);
        if(mysql_query(&mysql,sqlStr)!=0)
        {
            printf("#02:select error:%s\n%s\n",mysql_error(&mysql),sqlStr);
            return -1;
        }
        result=mysql_store_result(&mysql);
        if(result==NULL)
        {
            printf("result error:%s\n",mysql_error(&mysql));
            return -1;
        }
        row=mysql_fetch_row(result);
        if(row)
        {
            write(confd,"#02|0|LoginSuccess",18);
		printf("#02|0|LoginSuccess\n");
            sprintf(sqlStr,"update UserTb set OnlineFlag=1, confd='%d' where UserName='%s'",confd,uName);

            if(mysql_query(&mysql,sqlStr)!=0)
            {
                printf("#02updateerror:%s\n",mysql_error(&mysql));
                return -1;
            }
            sprintf(sqlStr,"select * from MessageTb where Recept='%s' and SendFlag!=1 and SendFlag!=0 order by SendTime",uName);
            if(mysql_query(&mysql,sqlStr)!=0)
            {
                printf("select error:%s\n%s\n",mysql_error(&mysql),sqlStr);
                return -1;
            }
            result=mysql_store_result(&mysql);
            if(result==NULL)
            {
                printf("result error:%s\n",mysql_error(&mysql));
                return -1;
            }
            while((row=mysql_fetch_row(result))!=NULL)//#
            {
                char message[1024]={0};
                int flag=atoi(*(row+3));
                if(flag==3)
                {
                    sprintf(message,"#03|%s|%s|%s\n",*row,*(row+2),*(row+4));//+2time,+4txt,rowSender,+1Recept
                    write(confd,message,strlen(message));
			printf("%s\n",message);
                }
                else if(flag==4)
                {
                    sprintf(message,"#04|3|%s",*row);
                    write(confd,message,strlen(message));
			printf("%s\n",message);
                }
                else if(flag==5)
                {
                    sprintf(message,"#05|%s|%s",*(row),*(row+4));
                    write(confd,message,strlen(message));
    			printf("%s\n",message);
                }
              
            }
            sprintf(sqlStr,"update MessageTb set SendFlag=1 where Recept='%s' and SendFlag=3",uName);
            if(mysql_query(&mysql,sqlStr)!=0)
                                printf("%s\n",mysql_error(&mysql));
			sprintf(sqlStr,"update MessageTb set SendFlag=0 where Recept='%s' and SendFlag!=3 and SendFlag!=1",uName);
        	if(mysql_query(&mysql,sqlStr)!=0)
                                printf("%s\n",mysql_error(&mysql));
		}
        else
        {
            write(confd,"#02|1|LoginError",16);
		printf("#02|1|LoginError\n");
        }
    }
    if(strcmp(type,"03")==0)//#03|Sender|Recept|txt
    {
        char sendUser[32]={0};
        char txt[32]={0};
        char message[1024]={0};
        char User[32]={0};
        sscanf(buf+4,"%[^|]|%[^|]|%s",User,sendUser,txt);
        char sqlStr[1024]={0};
        sprintf(sqlStr,"select confd,OnlineFlag from UserTb where UserName='%s'",sendUser);
        if(mysql_query(&mysql,sqlStr)!=0)
        {
            printf("select error:%s\n%s\n",mysql_error(&mysql),sqlStr);
            return -1;
        }
        result=mysql_store_result(&mysql);
        if(result==NULL)
        {
            printf("result error:%s\n",mysql_error(&mysql));
            return -1;
        }
        row=mysql_fetch_row(result);
        if(row)
        {
            int userconfd=atoi(*row);
            int onlineflag=atoi(*(row+1));
            time_t now=time(NULL);
            char timeStr[32]={0};
            strftime(timeStr,sizeof(timeStr),"%Y-%m-%d %H:%M:%S",localtime(&now));
            sprintf(sqlStr,"select * from FriendTb where friend_1='%s' and friend_2='%s'",User,sendUser);
            if(mysql_query(&mysql,sqlStr)!=0)
            {
                    printf("select error:%s\n%s\n",mysql_error(&mysql),sqlStr);
                    return -1;
            }
            result=mysql_store_result(&mysql);
            if(result==NULL)
            {
                printf("result error:%s\n",mysql_error(&mysql));
                return -1;
            }
            row=mysql_fetch_row(result);
            if(row)
            {
                    if(onlineflag)
                    {
                    sprintf(sqlStr,"insert into MessageTb values('%s','%s','%s',1,'%s')",User,sendUser,timeStr,txt);
                    if(mysql_query(&mysql,sqlStr)!=0)
                    {
                        printf("insert error:%s\n%s\n",mysql_error(&mysql),sqlStr);
                        return -1;
                    }
                    sprintf(message,"#03|%s|%s|%s",User,timeStr,txt);
                    write(userconfd,message,strlen(message));
			printf("%s\n",message);
                    }
                    else
                    {  
                        sprintf(sqlStr,"insert into MessageTb values('%s','%s','%s',3,'%s')",User,sendUser,timeStr,txt);
                        if(mysql_query(&mysql,sqlStr)!=0)
                        {
                             printf("#03insert error:%s\n%s\n",mysql_error(&mysql),sqlStr);
                            return -1;
                        }
                    }
            }
            else
            {
                write(confd,"#03|0",5);
		printf("#03|0\n");
            }
        }
        else
        {
            write(confd,"#03|empty user",14);
		printf("#03|empty user\n");
        }
    }
    if(strcmp(type,"04")==0)//#04|Sender|Recept
    {
        char Sender[32]={0};
        char message[1024]={0};
        char Recept[32]={0};
        sscanf(buf+4,"%[^|]|%s",Sender,Recept);
        char sqlStr[1024]={0};
        sprintf(sqlStr,"select * from UserTb where UserName='%s'",Recept);
        if(mysql_query(&mysql,sqlStr)!=0)
        {
            printf("#04select error:%s\n%s\n",mysql_error(&mysql),sqlStr);
            return -1;
        }
        result=mysql_store_result(&mysql);
        if(result==NULL)
        {
            printf("result error:%s\n",mysql_error(&mysql));
            return -1;
        }
        row=mysql_fetch_row(result);
        if(row)
        {
            int userconfd=atoi(*(row+3));
            int OnlineFlag=atoi(*(row+2));
            sprintf(sqlStr,"select * from FriendTb where friend_1='%s' and friend_2='%s'",Sender,Recept);
            if(mysql_query(&mysql,sqlStr)!=0)
            {
                printf("#04select error:%s\n%s\n",mysql_error(&mysql),sqlStr);
                return -1;
            }
            result=mysql_store_result(&mysql);
            if(result==NULL)
            {
                printf("result error:%s\n",mysql_error(&mysql));
                return -1;
            }
            row=mysql_fetch_row(result);
            if(row)
	{
                write(confd,"#04|0",5);
		printf("#04|0\n");
	}
            else
            {
                sprintf(sqlStr,"select * from MessageTb where SendFlag=4 and Sender='%s' and Recept='%s'",Sender,Recept);
                if(mysql_query(&mysql,sqlStr)!=0)
                {
                    printf("#04select error:%s\n%s\n",mysql_error(&mysql),sqlStr);
                        return -1;
                }
                result=mysql_store_result(&mysql);
            if(result==NULL)
            {
                printf("result error:%s\n",mysql_error(&mysql));
                return -1;
            }
            row=mysql_fetch_row(result);
            if(row)
		{
            	write(confd,"#04|1",5);
		printf("04|1\n");
		}
            else
            {
                sprintf(sqlStr,"insert into MessageTb values('%s','%s',now(),4,'0')",Sender,Recept);
                if(mysql_query(&mysql,sqlStr)!=0)
                {
                        printf("#04insert error:%s\n%s\n",mysql_error(&mysql),sqlStr);
                        return -1;
                }
                if(OnlineFlag)
                {
                        sprintf(message,"#04|3|%s",Sender);
                        write(userconfd,message,strlen(message));
			printf("%s\n",message);
                }
            }
            }
        }
        else
        {
            write(confd,"#04|2",5);
		printf("#04|2\n");
        }
    }
    if(strcmp(type,"05")==0)
    {
        char Sender[32];
        char Recept[32];
        char mark;
        char sqlStr[1024];
        mark=buf[4];
        char message[1024];
        sscanf(buf+6,"%[^|]|%s",Sender,Recept);
        if(mark=='0')
        {
            sprintf(message,"#05|%s|0",Recept);
            sprintf(sqlStr,"select confd,OnlineFlag from UserTb where UserName='%s'",Sender);
            if(mysql_query(&mysql,sqlStr)!=0)
            {
                printf("#05select error:%s\n%s\n",mysql_error(&mysql),sqlStr);
                return -1;
            }
            result=mysql_store_result(&mysql);
            if(result==NULL)
            {
                printf("result error:%s\n",mysql_error(&mysql));
                return -1;
            }
            row=mysql_fetch_row(result);
            if(atoi(*(row+1))==0)
            {
                sprintf(sqlStr,"insert into MessageTb values('%s','%s',now(),5,'0')",Recept,Sender);
                if((mysql_query(&mysql,sqlStr)!=0))
                {
                    printf("#05insert error:%s\n%s\n",mysql_error(&mysql),sqlStr);
                    return -1;
                }
            }
            else
            {
                write(atoi(*row),message,strlen(message));
		printf("%s\n",message);
            }
        }
        else
        {
            sprintf(message,"#05|%s|1",Recept);
            sprintf(sqlStr,"select confd,OnlineFlag from UserTb where UserName='%s'",Sender);
            if(mysql_query(&mysql,sqlStr)!=0)
            {
                printf("#05select%s\n%s\n",mysql_error(&mysql),sqlStr);
            }
            result=mysql_store_result(&mysql);
            if(result==NULL)
            {
                printf("result error:%s\n",mysql_error(&mysql));
                return -1;
            }
            row=mysql_fetch_row(result);
            if(atoi(*(row+1))==0)
            {
                sprintf(sqlStr,"insert into MessageTb values('%s','%s',now(),5,'1')",Recept,Sender);
              
                if(mysql_query(&mysql,sqlStr)!=0)
                {
                    printf("#05insert error:%s\n%s\n",mysql_error(&mysql),sqlStr);
                }
            }
            else
            {
                write(atoi(*row),message,strlen(message));
		printf("%s\n",message);
            }
            sprintf(sqlStr,"insert into FriendTb values('%s','%s')",Sender,Recept);
            if(mysql_query(&mysql,sqlStr)!=0)
            {
                printf("#05insert error:%s\n%s\n",mysql_error(&mysql),sqlStr);
                return -1;
            }
            sprintf(sqlStr,"insert into FriendTb values('%s','%s')",Recept,Sender);
            if(mysql_query(&mysql,sqlStr)!=0)
                printf("#05insert error:%s\n%s\n",mysql_error(&mysql),sqlStr);
        }
    }
    if(strcmp(type,"06")==0)
    {
            char friend_1[32];
            char friend_2[32];
            sscanf(buf+4,"%[^|]|%s",friend_1,friend_2);
            char sqlStr[1024];
            sprintf(sqlStr,"select * from FriendTb where friend_1='%s' and friend_2='%s'",friend_1,friend_2);
            if(mysql_query(&mysql,sqlStr)!=0)
            {
                    printf("#06selecterror:%s\n",mysql_error(&mysql));
 					return -1;
            }
            result=mysql_store_result(&mysql);
            row=mysql_fetch_row(result);
            if(row!=NULL)
            {
                    sprintf(sqlStr,"delete from FriendTb where friend_1='%s' and friend_2='%s'",friend_1,friend_2);
                    if(mysql_query(&mysql,sqlStr)!=0)
                            printf("#06deleteerror:%s\n",mysql_error(&mysql));
                    sprintf(sqlStr,"delete from FriendTb where friend_1='%s' and friend_2='%s'",friend_2,friend_1);
                    if(mysql_query(&mysql,sqlStr)!=0)
                            printf("#06deleteerror:%s\n",mysql_error(&mysql));
                    printf("#06|1\n");
                    write(confd,"#06|1",5);
			printf("#06|1");
            }
            else
		{	printf("#06|0\n");
                    write(confd,"#06|0",5) ;
			printf("#06|0");
		}
    }
    if(strcmp(type,"07")==0)
	{
		char uName[32],uname[32];
		sscanf(buf+4,"%[^|]|",uName);
		char sqlStr[1024];
		sprintf(sqlStr,"select friend_2 from FriendTb where friend_1='%s'",uName);
		if(mysql_query(&mysql,sqlStr)!=0)
			printf("#07error:%s\n",mysql_error(&mysql));
		result=mysql_store_result(&mysql);
		int temp=0;
		while((row=mysql_fetch_row(result))!=NULL)
		{
			char sqlStr_1[1024];
			char message_1[1024];
			MYSQL_RES *result_1=NULL;
			MYSQL_ROW row_1;
			sprintf(sqlStr_1,"select OnlineFlag from UserTb where UserName='%s'",*row);
			printf("%s\n",sqlStr);
			if(mysql_query(&mysql,sqlStr_1)!=0)
				printf("#07.1error:%s\n",mysql_error(&mysql));
			result_1=mysql_store_result(&mysql);
			row_1=mysql_fetch_row(result_1);
			sprintf(message_1,"#07|%s|%s",*row,*row_1);
			write(confd,message_1,strlen(message_1));
			printf("%s\n",message_1);
			temp++;
			printf("temp=%d\n",temp);
			mysql_free_result(result_1);
		}
	}
    if(strcmp(type,"08")==0)//Chat Record
 	{
 		char Current[32];
        char Query[32];
        char message[1024];
        sscanf(buf+4,"%[^|]|%s",Current,Query);
        char sqlStr[1024]={0};
        sprintf(sqlStr,"select * from UserTb where UserName='%s'",Query);
        if(mysql_query(&mysql,sqlStr)!=0)
        {
            printf("#08select error:%s\n%s\n",mysql_error(&mysql),sqlStr);
            return -1;
        }
        result=mysql_store_result(&mysql);
        if(result==NULL)
        {
            printf("result error:%s\n",mysql_error(&mysql));
            return -1;
        }
        row=mysql_fetch_row(result);
        if(row)
        {
        	sprintf(sqlStr,"select * from  MessageTb where ((Sender='%s' and Recept='%s') or (Sender='%s' and Recept='%s')) and (SendFlag=1 or SendFlag=3)",Current,Query,Query,Current);
        
            if(mysql_query(&mysql,sqlStr)!=0)
            {
                printf("#08select error:%s\n",mysql_error(&mysql));
                return -1;
            }
            result=mysql_store_result(&mysql);
            if(result==NULL)
            {
                printf("result error:%s\n",mysql_error(&mysql));
                return -1;
            }
            while((row=mysql_fetch_row(result))!=NULL)//#
            {
                char message[1024]={0};
                sprintf(message,"#08|1|%s|%s|%s|%s",*row,*(row+1),*(row+2),*(row+4));
                write(confd,message,strlen(message));
		printf("%s\n",message);
             
            }
		}
		else
		{
			write(confd,"#08|0",5);
			printf("#08|0\n");
		}
	}
    
    mysql_close(&mysql);
    return 1;
 
}
int offOnline(int confd)
{
    MYSQL mysql;
    mysql_init(&mysql);
    mysql_real_connect(&mysql,"127.0.0.1","root","shenboyuan","qq",0,NULL,0);
    char sqlStr[1024]={0};
    sprintf(sqlStr,"update UserTb set OnlineFlag=0 ,confd=-1 where confd='%d'",confd);
    if(mysql_query(&mysql,sqlStr)!=0)
    {
        printf("offOnlineError:%s\n",mysql_error(&mysql));
        return -1;
    }
    mysql_close(&mysql);
    printf("offline\n");
}
int main()
{
    int lisfd=socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in sevaddr;
    sevaddr.sin_family=AF_INET;
    sevaddr.sin_port=htons(9988);
    sevaddr.sin_addr.s_addr=inet_addr("192.168.164.128");
 
 
    int maxfd=0;
    fd_set allset,reset;
    FD_ZERO(&allset);
    int clifd[1024]={0};
    memset(clifd,-1,sizeof(clifd));
    int confd=0;
    int curi=0,i=0;
 
    if(bind(lisfd,(struct sockaddr*)&sevaddr,sizeof(sevaddr))!=0)
    {
        printf("binderror\n");
        return -1;
    }
    listen(lisfd,3);
 
 
    FD_SET(lisfd,&allset);
    if(maxfd<lisfd)
        maxfd=lisfd;
    
    while(1)
    {
        reset=allset;
        int nready=select(maxfd+1,&reset,NULL,NULL,NULL);
        if(nready<=0)
        {
            printf("select error\n");
            return -1;
        }
        if(FD_ISSET(lisfd,&reset))
        {
            confd=accept(lisfd,NULL,NULL);
            if(confd==-1)
            {
                printf("accept error\n");
                return -1;
            }
            FD_SET(confd,&allset);
            if(confd>maxfd)
                maxfd=confd;
            for(i=0;i<curi;i++)
            {
                if(clifd[i]==-1)
                {
                    clifd[i]=confd;
                    break;
                }
            }
            if(curi==i)
            {
                if(curi==1024)
                {
                    printf("max fd\n");
                    return -1;
                }
                else
                    clifd[curi++]=confd;
            }
        }
        for(i=0;i<curi;i++)
        {
            char sqlStr[1024];
            confd=clifd[i];
            if(FD_ISSET(confd,&reset))
            {
                char buf[1024]={0};
                if(read(confd,buf,sizeof(buf))==0)
                {
                    clifd[i]=-1;
                    offOnline(confd);
                    continue;
                }
                handData(buf,confd);
            }
        }
    }
}